package com.jishucai.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private GenericFutureListener futureListener;

    private ScheduledFuture<?> scheduledFuture;

    private Bootstrap bootstrap;

    public HeartBeatHandler(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        randomSend(ctx.channel());
    }

    private void randomSend(Channel channel) {
        int heartBeatInterval = new Random().nextInt(7) + 1;
        System.out.println(heartBeatInterval + "秒后发送心跳消息");

        scheduledFuture = channel.eventLoop().schedule(() -> {
            if (channel.isActive()) {
                System.out.println("向服务器发送心跳");
                channel.writeAndFlush("~PING~");
            } else {
                System.out.println("与服务器的连接已断开");
            }
        }, heartBeatInterval, TimeUnit.SECONDS);

        futureListener = (future) -> {
            randomSend(channel);
        };

        scheduledFuture.addListener(futureListener);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        scheduledFuture.removeListener(futureListener);

        System.out.println("Reconnecting...");

        bootstrap.connect("localhost",8888).sync();

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接收到服务端发来的消息:" + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

